const category = require('../../models/good/category');
class CategoryService {
    static async getCategoryList({ pageNum = 1, pageSize = 10 }, data) {
        const query = {
            ...(data?.name && { name: { $regex: data.name, $options: 'i' } }),
            ...(data?.parentId && { parentId: data.parentId }),
        };

        const skip = (pageNum - 1) * pageSize;
        const limit = pageSize;
        const total = await category.countDocuments(query);
        const categoryList = await category.find(query).skip(skip).limit(limit).populate("parentIds").lean();
        return {
            total,
            page: +pageNum,
            totalPages: Math.ceil(total / pageSize),
            list: categoryList
        };
    }
    static async getCategoryById(categoryId) {
        //通过递归无限获取父级id 

        return await category.findById(categoryId).populate("parentIds").lean();
    }


    static async getCategoryByParentId(parentId) {
        return await category.find({ parentId }).lean();
    }

    static async createCategory(categoryData) {
        return await category.create(categoryData);
    }
    static async updateCategory(categoryId, categoryData) {
        return await category.findByIdAndUpdate(categoryId, { $set: categoryData }, { new: true });
    }
    static async deleteCategory(categoryId) {
        return await category.findByIdAndDelete(categoryId);
    }
} module.exports = CategoryService;
